package org.campuscontent.io;

import java.io.DataInputStream; 
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.security.Security;

public class PHPQuery
{
    private URL url;

    private QueryString query;

    public PHPQuery( String url )
    {
//        System.setProperty("java.protocol.handler.pkgs",
//        "com.sun.net.ssl.internal.www.protocol");
//        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        
    	URL tmpURL;

        try
        {
            tmpURL = new URL( url );
        }
        catch ( MalformedURLException ex )
        {
            System.err.println( "Usage: java FormPoster url" );
            return;
        }

        if ( !tmpURL.getProtocol().toLowerCase().startsWith( "http" ) )
        {
            throw new IllegalArgumentException( "Posting only works for http URLs" );
        }
        this.url = tmpURL;

        query = new QueryString();
    }

    public void add( String name, String value )
    {
        query.add( name, value );
    }

    public URL getURL()
    {
        return this.url;
    }

    public DataInputStream read() throws IOException
    {

        URLConnection urlConn = url.openConnection();
        DataInputStream dis = new DataInputStream( urlConn.getInputStream() );

        return dis;
    }

    public DataInputStream query() throws IOException
    {

        // String result, line;
        DataInputStream dis;

        // open the connection and prepare it to POST
        URLConnection urlConn = url.openConnection();
        urlConn.setDoOutput( true );

        OutputStreamWriter out = new OutputStreamWriter( urlConn.getOutputStream(), "ASCII" );

        // The POST line, the Content-type header,
        // and the Content-length headers are sent by the URLConnection.
        // We just need to send the data
        out.write( query.toString() );
        out.write( "\r\n" );
        out.flush();
        out.close();

        // Get the response

        // result = "";

        dis = new DataInputStream( urlConn.getInputStream() );
        // while ((line = dis.readLine()) != null) {
        // result += line;
        // }
        // dis.close();

        return dis;
    }

}
